package com.maisonliberte.util;

import java.io.FileInputStream;
import java.util.Map;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;


public class NetUtil {
	
	public static void ftpUploadFile(Map<String, String> fileList, String addr, String uid, String pwd) throws Exception{
		
			
		
			
		for(String src : fileList.keySet()){
			
			FTPClient fp = new FTPClient();
			FileInputStream is = null;
			
			try {
				
				fp.connect(addr);
				if (!FTPReply.isPositiveCompletion(fp.getReplyCode())) { 
					System.out.println("connection failed");
					System.exit(1); 
				}
	
				if (fp.login(uid, pwd) == false) { 
					System.out.println("login failed");
					System.exit(1); 
				}
				
				fp.setConnectTimeout(100);
				fp.enterLocalActiveMode();
				fp.setFileTransferMode(FTPClient.BINARY_FILE_TYPE);
				fp.setTcpNoDelay(true);
				
				is = new FileInputStream(src.trim());
				fp.sendCommand("-O");
				//System.out.println(fp.getReplyStrings() + " Overwrite File");
				
				if(!fp.storeFile(fileList.get(src).trim(), is)){
					System.out.println(fileList.get(src).trim() + " FTP PUT FAILED");
					//throw new Exception("failed to upload");
				}
				is.close();
				System.out.println(fileList.get(src).trim() + " FTP PUT COMPLETED");		
				
				
			} catch(RuntimeException re) {
				throw re;
			} catch (Exception e) {
				throw e;
			} finally {
				is.close();
				fp.logout();
				fp.disconnect();
			}
			
		}
		
	}
	
}
